package com.saas.ability.core.base.exception;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.saas.ability.core.base.constant.retcode.RetCode;
import com.saas.ability.core.base.protocol.RespOutput;
import com.saas.ability.core.base.protocol.SimpleOutput;

/**
 * 统一异常处理
 *
 *
 */

@ControllerAdvice
public class GlobalExceptionHandler {

	Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

	@ExceptionHandler(value = { Exception.class })
	@ResponseBody
	public Object exceptionHandler(Exception e, HttpServletResponse response) {
		if (e instanceof VerificationException) {
			logger.error("版本检验错误,msg:{}", e.getMessage(),e);
			VerificationException ve = (VerificationException) e;
			return new SimpleOutput(ve.getRetCode(), ve.getMessage());
		}else if (e instanceof VersionException) {
			logger.error("版本验证错误,msg:{}", e.getMessage(),e);
			VersionException ve = (VersionException) e;
			return new SimpleOutput(ve.getRetCode(), ve.getMessage());
		}else if (e instanceof OriginException) {
			logger.error("来源错误,msg:{}", e.getMessage(),e);
			OriginException ve = (OriginException) e;
			return new SimpleOutput(ve.getRetCode(), ve.getMessage());
		}else if (e instanceof ServiceException) {
			logger.error("服务器发送不可预期的错误,msg:{}", e.getMessage(),e);
			ServiceException ve = (ServiceException) e;
			return new SimpleOutput(ve.getRetCode(), ve.getMessage());
		}else if(e instanceof RespException){
			RespException ve = (RespException) e;
			RespOutput respOutput = new RespOutput(ve.getStatus(), ve.getInfo(),"");
			return respOutput;
		}else if(e instanceof AuthenticateException){
			AuthenticateException ve = (AuthenticateException) e;
			return new SimpleOutput(ve.getRetCode(), ve.getMessage());
		}
		logger.error("异常错误,msg:{}", e.getMessage(), e);
		return new SimpleOutput(RetCode.FAIL.retCode, RetCode.FAIL.message);
	}
}
